import { getCoupListFun } from '../requets/coupFun'
import { requerconetnt, requerconetntAll } from '../utils/requestContent'
import { getUrlTabId } from '../utils/tools'
import { getShopInfoData } from '../api/coupContent'
import { upcheackcoupstatus } from '../api/dlyApis'
// 初始化的活动

// 自动开始 取消掉
setInterval(() => {
    init_run_auto()
}, 60000 * 120) // 两小时 激活一次程序

let oldShopData = null

// runTime 或 继续下一轮的计时器
let oyserNums = null


// 循环到第N个任务
let startIndex = 0

// 保存浏览器窗口ID信息
let qureyGterId = null


let isChengeConfig = false // 是否更改了配置

export function getQureyGterId() {
    return qureyGterId
}



// 保存用户店铺信息
let userShopData = null
inoutertShopData()
function inoutertShopData() {
    const stopDataInfos = localStorage.getItem('stopDataInfos')
    try {
        if (stopDataInfos) {
            userShopData = JSON.parse(stopDataInfos)
        }
    } catch (error) {

    }
}
// 创建任务的状态
let runSetInterConter = false
export function setRunStatusFun(status) {
    console.log('创建状态', status)
    // 正在创建的状态
    runSetInterConter = status
}
let runenter = null
function init_run_auto() {
    if (!codeRunStatus && !runSetInterConter) {
        // console.log('挤进来了1')
        if (runenter) {
            clearTimeout(runenter)
            runenter = null
        }
        runenter = setTimeout(() => {
            if (!codeRunStatus && !runSetInterConter) {
                // console.log('挤进来了2')
                if (runenter) {
                    clearTimeout(runenter)
                    runenter = null
                }
                runenter = setTimeout(() => {
                    if (!codeRunStatus && !runSetInterConter) {
                        // console.log('挤进来了3')
                        startIndex = 0
                        chrome.storage.local.set({
                            couplistDatas: ''
                        })
                        runSterOterr(true)
                    } else {
                        console.log('代码在运行 不可继续3， init_run_auto')
                    }
                }, 1000)

            } else {
                console.log('代码在运行 不可继续2， init_run_auto')
            }
        }, 1000)

    } else {
        console.log('代码在运行 不可继续， run_auto_set_coupon')
    }
}

let codeRunStatus = false
let clearConter = null
const adConyer = {
    add_coupon_config: {
        allow: { script: true },
        exec: async (request, sender, sendResponse) => {
            getShopIdcontent(request).then(res => {

                request.configs && request.configs.length > 0 && request.configs.forEach(item => {
                    item.noCounpGoodList = item.noCounpGoodList || [] // 没有优惠券 正在被设置的商品
                    item.coupGoods = item.coupGoods || [] // 被优惠券占用 还不可以进行的
                    item.runScususe = item.runScususe || [] // 已经设置的活动商品
                    // item.runStatus = item.runStatus ? item.runStatus : 'stop'
                })
                // console.log('request.configs', request.configs)
                request.configs.forEach(item => {
                    const { discountType } = item
                    if (discountType === 1) {
                        item.sorterConter = 15
                    }
                    if (discountType === 2) {
                        item.sorterConter = (item.creditConf.threshold - item.creditConf.credit) / item.creditConf.threshold * 10
                    }
                    if (discountType === 3) {
                        item.sorterConter = item.creditConf.discount
                    }
                })
                request.configs.sort((a, b) => {
                    return a.sorterConter - b.sorterConter
                })
                request.configs.forEach((res, index) => {
                    res.sort = index
                })
                startIndex = 0
                isChengeConfig = true

                // 修改配置后需要立即走一遍
                if (clearConter) {
                    clearTimeout(clearConter)
                    clearConter = null
                }
                clearConter = setTimeout(() => {
                    if (request.configs.length > 0 && !runSetInterConter) {
                        chrome.storage.local.set({
                            couplistDatas: ''
                        })
                        // chrome.storage.local.set({
                        //     couplistDatas: ''
                        // })
                        if (oyserNums) {

                            clearTimeout(oyserNums)
                            setTimeout(() => {
                                init_run_auto()
                            }, 3000);
                            oyserNums = null
                        }
                        if (clearRunStatusTime) {
                            clearTimeout(clearRunStatusTime)
                            clearRunStatusTime = null
                            codeRunStatus = false

                        }
                    }

                    if (!request.configs || request.configs.length === 0) {
                        // 清空任务队列 重新开始
                        chrome.storage.local.set({
                            couplistDatas: ''
                        })
                        // chrome.storage.local.set({
                        //     couplistDatas: ''
                        // })
                        if (oyserNums) {

                            clearTimeout(oyserNums)
                            oyserNums = null
                        }
                        codeRunStatus = false
                        if (clearRunStatusTime) {
                            clearTimeout(clearRunStatusTime)
                            clearRunStatusTime = null
                        }

                    }
                }, 2000)

                setLoacsConfigFun(request.configs)
            })

            sendResponse && sendResponse('add_coupon_config');
            return true
        }
    },
    run_auto_set_coupon: {
        allow: { script: true },
        exec: (request, sender, sendResponse) => {
            init_run_auto()

            sendResponse && sendResponse('run_auto_set_coupon');
            return true
        }
    },
    get_auto_set_coupon: {
        allow: { script: true },
        exec: (request, sender, sendResponse) => {
            getShopIdcontent(request).then(res => {
                setLoacsConfigFun(getLocStopConfigFun()).then(res => {
                    sendResponse && sendResponse('get_auto_set_coupon');
                })
            })

            sendResponse && sendResponse('get_auto_set_coupon');
            return true
        }
    },
    save_user_login_shop_data: {
        allow: { script: true },
        exec: (request, sender, sendResponse) => {
            setTimeout(() => {
                getShopIdcontent(request).then(_ => {
                    console.log('_', _)
                    init_run_auto()
                })
            }, 500)
            getUserShopLoginStatus()
            sendResponse && sendResponse('save_user_login_shop_data');
            return true
        }
    },
    get_add_new_prd: {
        allow: { script: true },
        exec: (request, sender, sendResponse) => {
            console.log('sender.tab?.id', sender.tab?.id)
            requerconetntAll('2.0.0', 'getNewPrd', sender.tab?.id)
            getShopIdcontent(request)
            sendResponse && sendResponse('get_add_new_prd');
        }
    },
    save_user_jwt: {
        allow: { script: true },
        exec: (request, sender, sendResponse) => {
            localStorage.setItem('user_jwt', request.jwt)
            sendResponse && sendResponse('save_user_jwt');
        }
    },
    save_run_dent_time: {
        allow: { script: true },
        exec: (request, sender, sendResponse) => {
            localStorage.setItem('run_dent_time', request.time)
            sendResponse && sendResponse('save_run_dent_time');
        }
    }
}
// 检查抖店的登陆状态
getUserShopLoginStatus()
let getShopRunTimeStatus
function getUserShopLoginStatus() {
    if (getShopRunTimeStatus) {
        clearInterval(getShopRunTimeStatus)
        getShopRunTimeStatus = null
    }
    getShopRunTimeStatus = setInterval(() => {
        getShopIdcontent().then(_ => {
            // console.log('检查店铺结果', _)
            if (_.code == 10008) {
                const getSengErrpconter = localStorage.getItem('loginerrsmscode')
                const getShopData = localStorage.getItem('userShopDataCopy')
                try {
                    const shopData = JSON.parse(getShopData)


                    if (!getSengErrpconter) {

                        localStorage.setItem('loginerrsmscode', JSON.stringify({
                            time: new Date().getTime(),
                            status: true
                        }))
                        console.log('没有发送过')
                        upcheackcoupstatus({
                            type: 'loginerr',
                            num: 0,
                            shop_name: shopData.shop_name
                        }).then(res => {
                            console.log('登陆失效通知', res)
                        })
                        return
                    }
                    try {
                        const jsonData = JSON.parse(getSengErrpconter)
                        if (new Date().getTime() >= (jsonData.time + 1000 * 60 * 60 * 1)) {
                            console.log('已经过期一个小时 重新发送一个')
                            upcheackcoupstatus({
                                type: 'loginerr',
                                num: 0,
                                shop_name: shopData.shop_name
                            }).then(res => {
                                console.log('登陆失效通知', res)
                            })
                            localStorage.setItem('loginerrsmscode', JSON.stringify({
                                time: new Date().getTime(),
                                status: true
                            }))
                            return
                        }
                    } catch (error) {
                        localStorage.setItem('loginerrsmscode', JSON.stringify({
                            time: new Date().getTime(),
                            status: false
                        }))
                    }

                    // upcheackcoupstatus({
                    //     type: 'createSuccess',
                    //     num: data.allData.length,
                    //     shop_name: shopData.shop_name
                    // }).then(res => {
                    //     console.log('创建完成的通知', res)
                    // })
                } catch (error) {
                    console.log('error', error)
                }

            }
        })
    }, 1000 * 60 * 30)//30分钟检查一次抖店的登陆状态

}


let clearRunStatusTime = null // 超时没有运行中的情况需要关闭
function runSterOterr(runOne = true, alter = false) {
    console.log('调用开始')

    try {
        if (isChengeConfig) {
            // 重新更新任务
            isChengeConfig = false
            startIndex = 0
            console.log('修改过配置 需要从头开始任务')
            chrome.storage.local.set({
                couplistDatas: ''
            })
        }
        const dataJsons = getLocStopConfigFun()

        const getAllconfigData = dataJsons.filter(item => item.status == 0 || item.status == 7 || item.status == 6 || item.status == 9 || item.status == 13)

        const getStaPericonter = getAllconfigData[startIndex]// sortRuns[0]
        console.log('startIndex', startIndex, getStaPericonter, getAllconfigData)
        if (codeRunStatus && !alter && !runSetInterConter) {
            console.log('任务在运行， 不可重复')
            return
        }
        if (!getAllconfigData || !getAllconfigData.length) {
            console.log('没有可用任务 代码停止')
            codeRunStatus = false
            chrome.storage.local.set({
                couplistDatas: ''
            }) // 清空优惠券生效列表
            startIndex = 0
            if (clearRunStatusTime) {
                clearTimeout(clearRunStatusTime)
                clearRunStatusTime = null
            }
            if (oyserNums) {

                clearTimeout(oyserNums)
                oyserNums = null
            }
            return
        }
        codeRunStatus = true
        if (clearRunStatusTime) {
            clearTimeout(clearRunStatusTime)
            clearRunStatusTime = null
        }
        clearRunStatusTime = setTimeout(() => {
            codeRunStatus = false
            clearTimeout(clearRunStatusTime)
            clearRunStatusTime = null
            if (oyserNums) {

                clearTimeout(oyserNums)
                oyserNums = null
            }
            init_run_auto()

        }, 1000 * 60 * 60)
        if (startIndex === 0) {
            chrome.storage.local.set({
                couplistDatas: ''
            })
        }
        // getUrlTabId('https://fxg.jinritemai.com', 'https://fxg.jinritemai.com/ffa/marketing/coupon/home').then((tabId) => {
        //     // 自动打开对应页面00
        // })
        if (getStaPericonter) {

            getStaPericonter.status = getStaPericonter.status === 6 ? 6 : 7 // 等待进行
            setLoacsConfigFun(dataJsons)
            runOne && getCoupListFun(getStaPericonter, runScopter)
            return
        }

        chrome.storage.local.set({
            couplistDatas: ''
        })
        if (oyserNums) {

            clearTimeout(oyserNums)
            oyserNums = null
        }
        let MPTime = localStorage.getItem('run_dent_time')
        if (MPTime && !Number.isNaN(Number(MPTime)) && Number(MPTime) > 0) {
            MPTime = 1000 * 60 * Number(MPTime)
        } else {
            MPTime = 1000 * 60 * 1 // 默认1分钟
        }
        // console.log('等待时间', MPTime)
        // // 延时继续调用
        oyserNums = setTimeout(() => {
            clearTimeout(oyserNums)
            oyserNums = null
            startIndex = 0
            runSterOterr(true, true)
        }, MPTime); // MPTime 时间需要重新配置
    } catch (error) {
        console.log('error', error)
    }

}



function runScopter(data) {
    console.log('任务返回', data.type, startIndex)
    if (data && !data.code) {
        // runTingCheack()
        if (data.type == 'runTing') { // 有任务运行中 不用管
            // 需要通知修改规则
            startIndex = 0
            const getAddData = getLocStopConfigFun()
            const getFiter = getAddData.find(item => item.id == data.config.id)

            if (getAddData && getAddData.length > 0 && getFiter) {
                let succerrData = getFiter.succerrData || []
                let errDatas = getFiter.errDatas || []
                data.runData.succerrData && succerrData.push([...data.runData.succerrData])
                data.runData.errDatas && errDatas.push([...data.runData.errDatas])
                if (getFiter) {
                    getFiter.status = 1
                    getFiter.upDateTime = new Date()
                    getFiter.succerrData = succerrData
                    getFiter.errDatas = errDatas
                    getFiter.noCounpGoodList = data.config.noCounpGoodList
                    getFiter.coupGoods = data.config.coupGoods
                    getFiter.runScususe = data.config.runScususe
                    getFiter.getSelectGoods = data.config.getSelectGoods
                    getFiter.isOrdouters = data.isOrdouters

                    if (data.isOrdouters) {
                        getFiter.status = 9
                    }

                    setLoacsConfigFun(getAddData).then(res => {
                        // runOyetr()
                    })

                }
            }

        }
        if (data.type == 'runEnd') { // 任务运行结束 重新开始进行循环任务列表
            // runSterOterr()
            // return
            // 需要通知修改规则

            const getAddData = getLocStopConfigFun()

            if (getAddData && getAddData.length > 0) {
                const getFiter = getAddData.find(item => item.id == data.config.id)
                if (getFiter) {
                    getFiter.status = 2
                    getFiter.upDateTime = new Date()
                    getFiter.noCounpGoodList = data.config.noCounpGoodList
                    getFiter.coupGoods = data.config.coupGoods
                    getFiter.runScususe = data.config.runScususe
                    getFiter.getSelectGoods = data.config.getSelectGoods

                    getFiter.isOrdouters = data.isOrdouters
                    if (data.isOrdouters) {
                        getFiter.status = 6
                    }
                    startIndex = 0
                    setLoacsConfigFun(getAddData).then(res => {
                        chrome.storage.local.set({
                            couplistDatas: ''
                        })
                        // 创建成功后的通知
                        const getShopData = localStorage.getItem('userShopDataCopy')
                        // setTimeout(() => {
                        //     runSterOterr(true, true)
                        // }, 60000)
                        if (oyserNums) {

                            clearTimeout(oyserNums)
                            oyserNums = null
                        }
                        let MPTime = localStorage.getItem('run_dent_time')
                        if (MPTime && !Number.isNaN(Number(MPTime)) && Number(MPTime) > 0) {
                            MPTime = 1000 * 60 * Number(MPTime)
                        } else {
                            MPTime = 1000 * 60 * 1 // 默认1分钟
                        }
                        // // 延时继续调用
                        console.log('延时继续调用res', res, MPTime)
                        oyserNums = setTimeout(() => {
                            clearTimeout(oyserNums)
                            oyserNums = null
                            startIndex = 0
                            runSterOterr(true, true)
                        }, MPTime); // MPTime 时间需要重新配置
                        try {
                            const shopData = JSON.parse(getShopData)
                            if (data.allData.length) {
                                upcheackcoupstatus({
                                    type: 'createSuccess',
                                    num: data.allData.length,
                                    shop_name: shopData.shop_name.slice(0, 6)
                                }).then(res => {
                                    console.log('创建完成的通知', res)
                                })
                            }

                        } catch (error) {

                        }
                    })
                }
            }
        }
        if (data.type == 'runTime') {
            startIndex++
            runSterOterr(true, true)
        }
        if (data.type == 'runErroutime') {
            console.log('任务错误 5 秒后继续')
            setTimeout(() => {
                runSterOterr(true, true)
            }, 5000)
        }
        if (data.type == 'runEndTimeGlobMax') {

            const getAddData = getLocStopConfigFun()

            if (getAddData && getAddData.length > 0) {
                const getFiter = getAddData.find(item => item.id == data.config.id)
                getFiter.status = 13
                getFiter.errmsg = data.msg
                setLoacsConfigFun(getAddData).then(res => {
                    startIndex++
                    runSterOterr(true, true)
                })
            }
        }
        if (data.type == 'runEndTime') {
            const getAddData = getLocStopConfigFun()
            const getFiter = getAddData.find(item => item.id == data.config.id)
            getFiter.status = 11
            startIndex = 0
            setLoacsConfigFun(getAddData).then(res => {
                chrome.storage.local.set({
                    couplistDatas: ''
                })
                runSterOterr(true, true)
            })
        }
    }

}
// 获取任务列表
export function getLocStopConfigFun() {
    if (!userShopData) return []
    let getItemInfos = localStorage.getItem(`autoSetCoupon_${userShopData.id || '000000'}`)
    try {
        const dataJsons = JSON.parse(getItemInfos) || []
        return dataJsons
    } catch (error) {
        return []
    }

}

// 设置任务状态 并传递任务
function setLoacsConfigFun(data) {
    // console.log('设置任务状态 并传递任务00..00', data)
    return new Promise((resolve, reject) => {

        if (!userShopData) return resolve(true)
        localStorage.setItem(`autoSetCoupon_${userShopData.id || '000000'}`, JSON.stringify(data))
        // 通知到页面修改状态
        // console.log('触发设置状态', data)
        requerconetntAll(data, 'saveStoreges').then(res => {
            // console.log('数据更新完成', res)
            resolve(res)
        })

    })
}


function getShopIdcontent() {
    // 后期加入到检查是否登陆等短信验证
    return new Promise((resolve, reject) => {
        getUrlTabId('https://fxg.jinritemai.com', false, true).then((tabId) => {
            // console.log('tabId000', tabId)
            qureyGterId = tabId
            getShopInfoData().then(res => {
                // console.log('获取店铺信息', res)
                if (!res) {
                    return reject(false)
                }
                if (!res.code) {
                    userShopData = res.data
                    oldShopData = res.data
                    localStorage.setItem('userShopDataCopy', JSON.stringify(userShopData))
                } else {
                    userShopData = null
                }
                localStorage.setItem('userShopData', JSON.stringify(userShopData))
                resolve(res)
            })
        })

    })
}




export default adConyer